from opcua import Client
import time
from flask import Flask, request, jsonify
from flask_cors import CORS  # 导入CORS

# 配置服务器地址（根据实际情况修改）
url = "opc.tcp://localhost:4840"  # 示例地址

# 目标节点路径解析（根据实际服务器结构调整）

def connect_and_operate():
    client = Client(url)
    try:
        client.connect()
        
        # 通过节点id获取节点对象
        
        target_node = client.get_node("ns=2;i=2001")
        print("找到目标节点：", target_node)
        
        # 读取当前值
        value = target_node.get_value()
        print(f"当前值：{value} ({type(value)})")
        
        # 写入新值（假设是整型）
        new_value = value + 100 if isinstance(value, (int, float)) else 0
        target_node.set_value(new_value)
        print(f"已更新值：{new_value}")
        
    except Exception as e:
        print("操作失败：", e)
    finally:
        client.disconnect()

app = Flask(__name__)
CORS(app)  # 启用CORS，允许所有来源的访问

@app.route('/get', methods=['GET'])
def get_node_value():
    try:
        node_id = request.args.get('node_id')
        opcua_url = request.args.get('url', default='opc.tcp://localhost:4840')
        client = Client(opcua_url)
        client.connect()
        target_node = client.get_node(node_id)
        value = target_node.get_value()
        
        print(f"获取{node_id}，当前值：{value} ({type(value)})\n")
        return jsonify({'value': value, 'type': str(type(value))})
    except Exception as e:
        return jsonify({'error': str(e)}), 500
    finally:
        client.disconnect()

@app.route('/set', methods=['POST'])
def set_node_value():
    try:
        opcua_url = request.args.get('url', default='opc.tcp://localhost:4840')
        client = Client(opcua_url)
        client.connect()
        
        node_id = request.args.get('node_id')
        value = request.args.get('value')
        type = request.args.get('type', default='int')
        from opcua import ua

        if type == 'uint' or type == 'int' or type == 'number':
            value = ua.Variant(int(value), ua.VariantType.UInt32)
        elif type == 'float':
            value = ua.Variant(float(value), ua.VariantType.Float)
        
        target_node = client.get_node(node_id)
        target_node.set_value(value)
        print(f"设置{node_id}为{request.args.get('value')}\n")
        return jsonify({'status': 'success', 'new_value': request.args.get('value')})
    except Exception as e:
        return jsonify({'error': str(e)}), 500
    finally:
        client.disconnect()

@app.route('/hello', methods=['GET'])
def hello():
    return jsonify({'message': 'Hello, the server is up and running!'})

if __name__ == "__main__":
    app.run(host='10.149.158.72', port=8080)